package com.dh.blog.controllers;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dh.blog.service.ArticleService;
import com.dh.blog.utils.PagerUtils;
import com.dh.blog.vo.ArticlePagerVo;
import com.dh.blog.vo.ArticleVo;
import com.dh.blog.vo.CatalogVo;
import com.dh.blog.vo.CommentRowVo;
import com.dh.blog.vo.CommentVo;
import com.dh.blog.vo.PictureFileVo;
import com.ewei.web.common.exception.ErrorPageRuntimeException;
import com.ewei.web.common.exception.MessageRuntimeException;
import com.ewei.web.common.json.resolver.JsonModel;
import com.ewei.web.common.response.ResponseVO;
import com.ewei.web.common.utils.FileToolsBar;
import com.ewei.web.common.validator.SaveGroup;
/**
 * 文章控制器
 * @author David
 *
 */
@RequestMapping("/")
@Controller
public class ArticleController {
	@Resource(name="articleService")
	private ArticleService articleService;
	@Resource
	private Properties config;
	@RequestMapping(value="/article/{blog_id:\\w+}",method=RequestMethod.GET)
	public ModelAndView index(@PathVariable("blog_id")String blogId){
		return articlePager(blogId,null,1);
	}
	/**
	 * 查看文章的详细信息
	 * @return
	 */
	@RequestMapping(value="/article/{article_id:\\d+}/{blog_id:\\w+}",method=RequestMethod.GET)
	public ModelAndView info(@PathVariable("article_id")Integer articleId,@PathVariable("blog_id")String blogId){
		ArticleVo article = articleService.getArticleById(articleId);
		article.setId(articleId);
		ModelAndView model = new ModelAndView("articleInfo");
		model.addObject("article", article);
		model.addObject("dir",config.get("file_disk_dir"));
		return model;
	}
	/**
	 * 获得推荐文章
	 */
	@RequestMapping(value="/article/recommand/{blog_id:\\w+}",method=RequestMethod.GET)
	@ResponseBody
	public Object recommmands(@PathVariable("blog_id")String blogId){
		List<ArticleVo> articles = articleService.getCommandsByBlog(blogId);
		return new ResponseVO().setDatas(articles);
	}
	/**
	 * 分页获取文章
	 */
	@RequestMapping(value="/article/list/{pageNum:\\w+}/{blog_id:\\w+}",method=RequestMethod.GET)
	public ModelAndView articlePager(@PathVariable("blog_id")String blogId,
				@PathVariable("pageNum")Integer num){
		return articlePager(blogId,null,num);
	}
	@RequestMapping(value="/article/cly/{cly_id:\\w+}/list/{pageNum:\\w+}/{blog_id:\\w+}",method=RequestMethod.GET)
	@ResponseBody
	public ModelAndView articlePager(@PathVariable("blog_id")String blogId,
				@PathVariable("cly_id")Integer classifyId,@PathVariable("pageNum")Integer num){
		ArticlePagerVo pager = new ArticlePagerVo();
		int total = articleService.countByBlogAndQuery(blogId, classifyId);//计算总文章的数量
		int pages = total/pager.getSize();
		if(pager.getSize()*pages<total){
			pages++;
		}
		if(num>pages){//输入的页面索引超出了页数
			throw new IndexOutOfBoundsException();
		}
		pager.setBlogId(blogId);
		pager.setClassifyId(classifyId);
		pager.setOffset((num-1)*pager.getSize());//计算offset
		ArticlePagerVo resultPager = (ArticlePagerVo) articleService.getPagerByBlogAndQuery(pager);
		resultPager.setNum(num);
		resultPager.setTotal(total);
		resultPager.setPages(pages);
		PagerUtils.rangeMake(resultPager);
		ModelAndView model = new ModelAndView("article");
		model.addObject("pager", resultPager);
		model.addObject("classifyId",classifyId);//将类别id写入视图层
		return model;
	}
	/**
	 * 获取文章的图片信息
	 * @return
	 */
	@RequestMapping(value="/article/pics/{article_id:\\d+}",method=RequestMethod.GET)
	@ResponseBody
	public Object pics(@PathVariable("article_id")Integer articleId){
		List<PictureFileVo> list = 
				articleService.getPicsByArticle(articleId);
		return new ResponseVO().setDatas(list);
	}
	/**
	 * 对文章发表评论
	 * @return
	 */
	@RequestMapping(value="/article/comment",method=RequestMethod.POST)
	@ResponseBody
	public Object comment(@JsonModel @Validated(value=SaveGroup.class) CommentVo comment,BindingResult result){
		if(result.hasErrors()){
			return new ResponseVO().resolveError(result);
		}
		//TODO 要对第三方登陆的用户处理
		Integer articleId = comment.getArticleId();
		if(articleService.existsArticle(articleId) < 1){//判断该文章id是否存在
			return new ResponseVO().error("401", config.get("401"));
		}
		CommentVo parent = null;
		if(null != comment.getParentId() && !"".equals(comment.getParentId().trim()) &&
				(parent = articleService.getCommentById(comment.getParentId())) == null){//处理对评论的回复
			return new ResponseVO().error("402", config.get("402"));
		}
		if(null != parent){
			comment.setLevel(parent.getLevel()+1);
		}
		comment.setCreateTime(Calendar.getInstance().getTime());
		articleService.doComment(comment);
		return new ResponseVO();
	}
	/**
	 * 获得文章的评论楼
	 * @param articleId
	 * @return
	 */
	@RequestMapping(value="/article/comment/list/{article_id:\\d+}",method=RequestMethod.GET)
	@ResponseBody
	public Object getComments(@PathVariable("article_id")Integer articleId){
		List<CommentRowVo> list = articleService.getCommentsByArticle(articleId);
		return new ResponseVO().setDatas(list);
	}
	/**
	 * 获得文章目录信息
	 */
	@RequestMapping(value="/article/catalog/{article_id:\\w+}",method=RequestMethod.GET)
	public void catalog(@PathVariable("article_id")Integer articleId,HttpServletResponse response){
		CatalogVo catalog = articleService.getCatalogByArticle(articleId);
		String root = config.getProperty("file_disk_dir");
		String path = (root == null?"":root)+catalog.getDiskPath();
		try {
			FileToolsBar.readFileIntoStream(new File(path), 
					response.getOutputStream());
		} catch (IOException e) {
			throw new MessageRuntimeException(e);
		}
	}
	/**
	 * 测试用
	 * @return
	 */
	@RequestMapping(value="/article/test")
	public Object test(){
		return "article";
	}
}
